package com.szdtoo.test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;

public class MyRunable implements Runnable {

    String url = "jdbc:mysql://127.0.0.1:3306/shiro";
    String username = "root";
    String password = "";
    String name = "com.mysql.jdbc.Driver";

    @Override
    public void run() {

        String sql = "insert into users (username, password, password_salt) values (?,?,?)";
        Connection connection = getConnection();
        Long beginTime = new Date().getTime();
        PreparedStatement perpareStatement ;
        try {
            connection.setAutoCommit(false);
            perpareStatement = connection.prepareStatement(sql);
            for(int i = 0; i < 100000; i++) {
                perpareStatement.setString(1,"username"+i);
                perpareStatement.setString(2,"password"+i);
                perpareStatement.setString(3,"salt"+i);
                perpareStatement.addBatch();
            }
            perpareStatement.executeBatch();
            connection.commit();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        Long endTime = new Date().getTime();
        System.out.println("当前线程:"+Thread.currentThread().getName()+";"+"插入10w条数据花费时间:" + (endTime-beginTime)/1000 + "s");
    }

    public Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(name);
            connection = DriverManager.getConnection(url,username,password);
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }


}
